package edu.sdjzu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.sdjzu.config.JwtUtils;
import edu.sdjzu.dto.LoginRequest;
import edu.sdjzu.dto.RegisterRequest;
import edu.sdjzu.entity.User;
import edu.sdjzu.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;

    public String login(LoginRequest request) {
        User user = userMapper.selectOne(
                new QueryWrapper<User>().eq("username", request.getUsername())
        );

        if (user == null || !user.getPassword().equals(request.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        return jwtUtils.generateToken(user.getId(), user.getUsername());
    }

    public void register(RegisterRequest request) {
        User exist = userMapper.selectOne(
                new QueryWrapper<User>().eq("username", request.getUsername())
        );

        if (exist != null) {
            throw new RuntimeException("用户名已存在");
        }

        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword()); // 生产建议加密
        user.setNickname(request.getNickname());
        user.setEmail(request.getEmail());

        userMapper.insert(user);
    }
}

